#include "connect.h"
// 在头文件中定义静态成员变量的初始值
QString TCPClient::username = "乔杰";
QString TCPClient::userpasswd = "1234";
TCPClient::TCPClient(QObject *parent) : QObject(parent)
{

    socket = new QTcpSocket(this); // Use 'this' as parent for automatic deletion
    //connect(socket, &QTcpSocket::connected, this, &TCPClient::onConnected);
    //connect(socket, &QTcpSocket::readyRead, this, &TCPClient::onReadyRead);
    //connect(socket, &QTcpSocket::disconnected, this, &TCPClient::onDisconnected);
    //connect(socket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, &TCPClient::onError);

    socket->connectToHost(QHostAddress("124.223.70.196"), 10000);
}

TCPClient::~TCPClient()
{

}

void TCPClient::onConnected()
{
    qDebug() << "Connected to server successfully!";
    // Send a simple request message
    //QString request = "Hello, Server!";
    //socket->write(request.toUtf8());
}

bool TCPClient::onReadyRead()
{
    Student stu;
    int statusCode=0;
    // 接受数据
    QByteArray data = socket->readAll();
    qDebug() << "Received data from server:" << data;
    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error == QJsonParseError::NoError) {
        // JSON parsing was successful
        if (jsonDoc.isObject()) {
            QJsonObject jsonObject = jsonDoc.object();
            // Access the parsed JSON data
            stu. name = jsonObject["name"].toString();
            stu. ID = jsonObject["id"].toString();
            stu.Chinese = jsonObject["chinese"].toInt();
            stu.Math = jsonObject["math"].toInt();
            stu.English = jsonObject["english"].toInt();
            stu.Comprehension=jsonObject["uni"].toInt();
            stu.total=jsonObject["total"].toInt();
            stu.rank=jsonObject["rank"].toInt();
            statusCode=jsonObject["statusCode"].toInt();
            // Perform your desired operations with the data
        }
        else {
            // JSON data is not an object
            qDebug() << "Received JSON data is not an object";
        }
    }
    else {
        // JSON parsing failed
        qDebug() << "JSON parsing error: " << parseError.errorString();
    }
    if(statusCode==1)return true;
    else return false;
}

void TCPClient::onDisconnected()
{
    //qDebug() << "Disconnected from server!";
}

void TCPClient::onError(QAbstractSocket::SocketError socketError)
{
    QString err=socket->errorString();
    qDebug() << "Socket error:" << socketError;
    //QMessageBox::critical(0, "Socket Error", socket->errorString());
}

bool TCPClient::addstudent(const Student &stu)
{
    if (socket->isWritable()) {
        // 创建 JSON 对象
        QJsonObject jsonObject;

        // 插入元素，对应键值对

        //将数据转成json格式发送

        jsonObject["method"] ="ADD";
        jsonObject.insert("name",stu.name);
        jsonObject.insert("job","");
        jsonObject.insert("passwd",TCPClient::userpasswd);
        jsonObject.insert("account",TCPClient::username);
        jsonObject.insert("id",stu.ID);
        jsonObject.insert("chinese",stu.Chinese);
        jsonObject.insert("math",stu.Math);
        jsonObject.insert("uni",stu.Comprehension);
        jsonObject.insert("english",stu.English);



        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDocument(jsonObject);

        // 发送 JSON 文档
        socket->write(jsonDocument.toJson());
    } else {
        qDebug() << "Socket is not writable";
    }
    // 等待服务器响应
    socket->waitForReadyRead();
    QByteArray data = socket->readAll();
    qDebug() << "addstudent Received data from server:" << data;
    int statusCode=2;
    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error == QJsonParseError::NoError) {
        // JSON parsing was successful
        if (jsonDoc.isObject()) {
            QJsonObject jsonObject = jsonDoc.object();
            // 服务器返回的是一个 Student 对象
            statusCode=jsonObject["statusCode"].toInt();
        } else {
            // JSON data is not an object
            qDebug() << "Received JSON data is not an object";
        }
    } else {
        // JSON parsing failed
        qDebug() << "JSON parsing error: " << parseError.errorString();
    }
    if(statusCode==1)return true;
    else return false;
}

bool TCPClient::mydelete(QString ID)
{
    Student stu;
    if (socket->isWritable()) {
        // 创建 JSON 对象
        QJsonObject jsonObject;
        jsonObject["method"] ="DELETE";
        jsonObject.insert("name",stu.name);
        jsonObject.insert("job","");
        jsonObject.insert("passwd",TCPClient::userpasswd);
        jsonObject.insert("account",TCPClient::username);
        jsonObject.insert("id",ID);
        jsonObject.insert("chinese",stu.Chinese);
        jsonObject.insert("math",stu.Math);
        jsonObject.insert("uni",stu.Comprehension);
        jsonObject.insert("english",stu.English);


        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDocument(jsonObject);

        // 发送 JSON 文档
        socket->write(jsonDocument.toJson());
    }
    else {
        qDebug() << "Socket is not writable";
    }
    // 等待服务器响应
    socket->waitForReadyRead();
    QByteArray data = socket->readAll();
    qDebug() << "mydelete Received data from server:" << data;
    int statusCode=2;
    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error == QJsonParseError::NoError) {
        // JSON parsing was successful
        if (jsonDoc.isObject()) {
            QJsonObject jsonObject = jsonDoc.object();
            // 服务器返回的是一个 Student 对象
            statusCode=jsonObject["statusCode"].toInt();
        } else {
            // JSON data is not an object
            qDebug() << "Received JSON data is not an object";
        }
    } else {
        // JSON parsing failed
        qDebug() << "JSON parsing error: " << parseError.errorString();
    }
    if(statusCode==1)return true;
    else return false;
}

bool TCPClient::myupdate(const Student &stu)
{
    if (socket->isWritable()) {
        // 创建 JSON 对象
        QJsonObject jsonObject;
        jsonObject["method"] ="MODIFY";
        jsonObject.insert("name",stu.name);
        jsonObject.insert("job","");
        jsonObject.insert("passwd",TCPClient::userpasswd);
        jsonObject.insert("account",TCPClient::username);
        jsonObject.insert("id",stu.ID);
        jsonObject.insert("chinese",stu.Chinese);
        jsonObject.insert("math",stu.Math);
        jsonObject.insert("uni",stu.Comprehension);
        jsonObject.insert("english",stu.English);


        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDocument(jsonObject);

        // 发送 JSON 文档
        socket->write(jsonDocument.toJson());
    } else {
        qDebug() << "Socket is not writable";

    }
    // 等待服务器响应
    socket->waitForReadyRead();
    QByteArray data = socket->readAll();
    qDebug() << "myupdate Received data from server:" << data;
    int statusCode=2;
    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error == QJsonParseError::NoError) {
        // JSON parsing was successful
        if (jsonDoc.isObject()) {
            QJsonObject jsonObject = jsonDoc.object();
            // 服务器返回的是一个 Student 对象
            statusCode=jsonObject["statusCode"].toInt();
        } else {
            // JSON data is not an object
            qDebug() << "Received JSON data is not an object";
        }
    } else {
        // JSON parsing failed
        qDebug() << "JSON parsing error: " << parseError.errorString();
    }
    if(statusCode==1)return true;
    else return false;
}

bool TCPClient::search(QString ID, Student& stu)
{
    // 创建一个默认的 Student 对象作为返回值
    stu.ID = ID;

    if (socket->isWritable()) {
        // 创建 JSON 对象
        QJsonObject jsonObject;
        jsonObject["method"] = "GET";
        jsonObject.insert("name", stu.name);
        jsonObject.insert("job", "");
        jsonObject.insert("passwd", TCPClient::userpasswd);
        jsonObject.insert("account", TCPClient::username);
        jsonObject.insert("id", ID);
        jsonObject.insert("chinese", stu.Chinese);
        jsonObject.insert("math", stu.Math);
        jsonObject.insert("uni", stu.Comprehension);
        jsonObject.insert("english", stu.English);

        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDocument(jsonObject);

        // 发送 JSON 文档
        socket->write(jsonDocument.toJson());
    } else {
        qDebug() << "Socket is not writable";
        return false;
    }

    // 等待服务器响应
    socket->waitForReadyRead();
    QByteArray data = socket->readAll();
    //qDebug() << "search Received data from server:" << data;
    int statusCode = 2;
    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error == QJsonParseError::NoError) {
        // JSON解析成功
        if (jsonDoc.isObject()) {
            QJsonObject jsonObject = jsonDoc.object();
            // 服务器返回的是一个 Student 对象
            if (jsonObject.contains("data")) {
                QJsonValue dataValue = jsonObject["data"];
                if (dataValue.isString()) {
                    QJsonDocument dataDoc = QJsonDocument::fromJson(dataValue.toString().toUtf8(), &parseError);
                    if (parseError.error == QJsonParseError::NoError && dataDoc.isObject()) {
                        QJsonObject dataObject = dataDoc.object();
                        stu.name = dataObject["name"].toString();
                        stu.ID = dataObject["id"].toString();
                        stu.Chinese = dataObject["chinese"].toInt();
                        stu.Math = dataObject["math"].toInt();
                        stu.English = dataObject["english"].toInt();
                        stu.Comprehension = dataObject["uni"].toInt();
                        stu.total = dataObject["total"].toInt();
                        stu.rank = dataObject["rank"].toInt();
                        statusCode = jsonObject["statusCode"].toInt();
                    } else {
                        qDebug() << "Failed to parse 'data' value as JSON";
                    }
                } else {
                    qDebug() << "Received 'data' value is not a string";
                }
            } else {
                qDebug() << "Received JSON data does not contain 'data' key";
            }
        } else {
            // JSON data is not an object
            qDebug() << "Received JSON data is not an object";
        }
    } else {
        // JSON解析失败
        qDebug() << "JSON parsing error: " << parseError.errorString();
    }
    if (statusCode == 1) return true;
    else return false;
}


bool TCPClient::myregister(QString name,QString job,QString account,QString passwd)
{
    Student stu;
    if (socket->isWritable()) {
        // 创建 JSON 对象
        QJsonObject jsonObject;
        jsonObject["method"] ="REGISTER";
        jsonObject.insert("name",name);
        jsonObject["job"] =job;
        jsonObject["passwd"] =passwd;
        jsonObject["account"] =account;
        jsonObject.insert("id",stu.ID);
        jsonObject.insert("chinese",stu.Chinese);
        jsonObject.insert("math",stu.Math);
        jsonObject.insert("uni",stu.Comprehension);
        jsonObject.insert("english",stu.English);

        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDocument(jsonObject);

        // 发送 JSON 文档
        socket->write(jsonDocument.toJson());
    }
    else {
        qDebug() << "Socket is not writable";
        return false;
    }

    // 等待服务器响应
    socket->waitForReadyRead();
    QByteArray data = socket->readAll();
    qDebug() << "myregister Received data from server:" << data;
    int statusCode=2;
    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error == QJsonParseError::NoError) {
        // JSON parsing was successful
        if (jsonDoc.isObject()) {
            QJsonObject jsonObject = jsonDoc.object();
            // 服务器返回的是一个 Student 对象
            statusCode=jsonObject["statusCode"].toInt();
        } else {
            // JSON data is not an object
            qDebug() << "Received JSON data is not an object";
        }
    } else {
        // JSON parsing failed
        qDebug() << "JSON parsing error: " << parseError.errorString();
    }
    if(statusCode==1)return true;
    else return false;
}

bool TCPClient::mylogin()
{
    Student stu;
    if (socket->isWritable()) {
        // 创建 JSON 对象
        QJsonObject jsonObject;
        jsonObject.insert("method","LOGIN");
        jsonObject.insert("name",stu.name);
        jsonObject.insert("job","");
        jsonObject.insert("passwd",TCPClient::userpasswd);
        jsonObject.insert("account",TCPClient::username);
        jsonObject.insert("id",stu.ID);
        jsonObject.insert("chinese",stu.Chinese);
        jsonObject.insert("math",stu.Math);
        jsonObject.insert("uni",stu.Comprehension);
        jsonObject.insert("english",stu.English);

        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDocument(jsonObject);

        // 发送 JSON 文档
        socket->write(jsonDocument.toJson());
    }
    else {
        qDebug() << "Socket is not writable";
    }
    //return true;
    //return onReadyRead();
    // 等待服务器响应
    socket->waitForReadyRead();
    QByteArray data = socket->readAll();
    qDebug() << "mylogin Received data from server:" << data;
    int statusCode=2;
    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error == QJsonParseError::NoError) {
        // JSON parsing was successful
        if (jsonDoc.isObject()) {
            QJsonObject jsonObject = jsonDoc.object();
            // 服务器返回的是一个 Student 对象
            statusCode=jsonObject["statusCode"].toInt();
        } else {
            // JSON data is not an object
            qDebug() << "Received JSON data is not an object";
        }
    } else {
        // JSON parsing failed
        qDebug() << "JSON parsing error: " << parseError.errorString();
    }
    if(statusCode==1)return true;
    else return false;
}
int TCPClient::getstucount()
{
    int count=0;

    // 创建一个默认的 Student 对象
    Student stu;

    if (socket->isWritable()) {
        // 创建 JSON 对象
        QJsonObject jsonObject;
        jsonObject["method"] ="GETNUM";
        jsonObject.insert("name",stu.name);
        jsonObject.insert("job","");
        jsonObject.insert("passwd",TCPClient::userpasswd);
        jsonObject.insert("account",TCPClient::username);
        jsonObject.insert("id",stu.ID);
        jsonObject.insert("chinese",stu.Chinese);
        jsonObject.insert("math",stu.Math);
        jsonObject.insert("uni",stu.Comprehension);
        jsonObject.insert("english",stu.English);

        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDocument(jsonObject);

        // 发送 JSON 文档
        socket->write(jsonDocument.toJson());
    } else {
        qDebug() << "Socket is not writable";
    }

    // 等待服务器响应
    socket->waitForReadyRead();
    QByteArray data = socket->readAll();
    qDebug() << "getstucount Received data from server:" << data;

    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error == QJsonParseError::NoError) {
        // JSON parsing was successful
        if (jsonDoc.isObject()) {
            QJsonObject jsonObject = jsonDoc.object();
            // 服务器返回的是一个 Student 对象
            count=jsonObject["rank"].toInt();
        } else {
            // JSON data is not an object
            qDebug() << "Received JSON data is not an object";
        }
    } else {
        // JSON parsing failed
        qDebug() << "JSON parsing error: " << parseError.errorString();
    }
    return count;
}
bool TCPClient::getall(QVector<Student> &stus)
{
    // 创建一个默认的 Student 对象
    Student stu;
    if (socket->isWritable()) {
        // 创建 JSON 对象
        QJsonObject jsonObject;
        jsonObject["method"] = "ALL";
        jsonObject.insert("name",stu.name);
        jsonObject.insert("job","");
        jsonObject.insert("passwd",TCPClient::userpasswd);
        jsonObject.insert("account",TCPClient::username);
        jsonObject.insert("id",stu.ID);
        jsonObject.insert("chinese",stu.Chinese);
        jsonObject.insert("math",stu.Math);
        jsonObject.insert("uni",stu.Comprehension);
        jsonObject.insert("english",stu.English);

        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDocument(jsonObject);

        // 发送 JSON 文档
        socket->write(jsonDocument.toJson());
    } else {
        qDebug() << "Socket is not writable";
        return false;
    }

    // 等待服务器响应
    int statusCode=0;
    socket->waitForReadyRead();
    QString data = socket->readAll();
    qDebug() << "getall Received data from server:" << data;
    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data.toUtf8(), &parseError);
        // JSON解析成功

            QJsonArray jsonArray = jsonDoc.array();
            for (int i = 0; i < jsonArray.size(); ++i) {
                QJsonValueRef jsonValue = jsonArray[i];
                QJsonObject jsonObject = jsonValue.toObject();
                // 服务器返回的是一个 Student 对象
                stu.name = jsonObject["name"].toString();
                stu.ID = jsonObject["id"].toString();
                stu.Chinese = jsonObject["chinese"].toInt();
                stu.Math = jsonObject["math"].toInt();
                stu.English = jsonObject["english"].toInt();
                stu.Comprehension = jsonObject["uni"].toInt();
                stu.total = jsonObject["total"].toInt();
                stu.rank = jsonObject["rank"].toInt();
                stus.push_back(stu);
                qDebug()<<stu.Chinese;
            }
            QJsonObject jsonObject = jsonDoc.object();
            statusCode=jsonObject["statusCode"].toInt();

    if(statusCode==1)return true;
    else return false;
}
bool TCPClient::getall2(QVector<QString> &stus_ID)
{
    // 创建一个默认的 Student 对象
    Student stu;
    if (socket->isWritable()) {
        // 创建 JSON 对象
        QJsonObject jsonObject;
        jsonObject["method"] = "ALL";
        jsonObject.insert("name",stu.name);
        jsonObject.insert("job","");
        jsonObject.insert("passwd",TCPClient::userpasswd);
        jsonObject.insert("account",TCPClient::username);
        jsonObject.insert("id",stu.ID);
        jsonObject.insert("chinese",stu.Chinese);
        jsonObject.insert("math",stu.Math);
        jsonObject.insert("uni",stu.Comprehension);
        jsonObject.insert("english",stu.English);

        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument jsonDocument(jsonObject);

        // 发送 JSON 文档
        socket->write(jsonDocument.toJson());
    } else {
        qDebug() << "Socket is not writable";
    }

    // 等待服务器响应
    int statusCode=0;
    socket->waitForReadyRead();
    QByteArray data = socket->readAll();
    //qDebug() << "getall2 Received data from server:" << data;
    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error == QJsonParseError::NoError) {
        // JSON解析成功

        if (jsonDoc.isObject()) {

            QJsonObject jsonObject = jsonDoc.object();

            QJsonValue jsonData = jsonObject.value("data");
              stus_ID= extractNumbers(jsonData.toString());
               statusCode = jsonObject["statusCode"].toInt();
            }

}
    else {
        // JSON解析失败
        qDebug() << "JSON parsing error: " << parseError.errorString();
    }
    if(statusCode==1)return true;
    else return false;
}

QVector<QString> TCPClient::extractNumbers(const QString &str) {
    QVector<QString> numbers;

    // 使用正则表达式匹配数字字符串
    QRegularExpression regex("\\d+");
    QRegularExpressionMatchIterator matchIterator = regex.globalMatch(str);

    while (matchIterator.hasNext()) {
        QRegularExpressionMatch match = matchIterator.next();
        QString numberStr = match.captured();
        numbers.push_back(numberStr);
    }

    return numbers;
}
